package org.bp.ioc.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public final class ClassUtils {
    private static  final Logger LOGGER = LoggerFactory.getLogger(ClassUtils.class);

    /**
     * 获取当前线程的ClassLoader
     * @return
     */
    public static ClassLoader getClassLoader(){
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     * @param className 类名
     * @param isInit 是否执行静态代码块初始化 为了提高类的加载效率，该参数设为false
     * @return
     */
    public static Class<?> loadClass(String className,boolean isInit){
        Class<?> clazz ;
        try {
            clazz = Class.forName(className,isInit,getClassLoader());
        } catch (ClassNotFoundException e) {
            LOGGER.error(String.format("%s loaded failed ",className),e);
            throw new RuntimeException(e);
        }
        return clazz;
    }

    /**
     * 获取packageName下的所有class
     * @param packageName
     * @return
     */
    public static Set<Class<?>> getClassSet(String packageName){
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".","/"));
            while (urls.hasMoreElements()){
                URL url = urls.nextElement();
                if(ObjectUtils.isNotNull(url)){
                    String protocol = url.getProtocol();
                    if(protocol.equals("file")){
                        String packagePath = url.getPath().replace("%20", "");
                        addClass(classSet,packagePath,packageName);
                    }else if(protocol.equals("jar")){
                        //解压jar文件
                        JarURLConnection jarUrlConnection = (JarURLConnection) url.openConnection();
                        if(ObjectUtils.isNotNull(jarUrlConnection)){
                            JarFile jarFile = jarUrlConnection.getJarFile();
                            if(ObjectUtils.isNotNull(jarFile)){
                                Enumeration<JarEntry> jarEntries = jarFile.entries();
                                while (jarEntries.hasMoreElements()){
                                    JarEntry jarEntry = jarEntries.nextElement();
                                    String jarEntryName = jarEntry.getName();
                                    if(jarEntryName.endsWith(".class")){
                                        addClass(classSet,jarEntryName.substring(0,
                                                jarEntryName.lastIndexOf(".")).replace("/","."));
                                    }
                                }
                            }
                        }
                    }
                }
            }

        } catch (IOException e) {
            LOGGER.error("get class set failed",e);
            throw new RuntimeException(e);
        }

        return classSet;
    }

    /**
     * 从其余文件中加载class 
     * @param classSet
     * @param packagePath
     * @param packageName
     */
    private static void addClass(Set<Class<?>> classSet,String packagePath, String packageName){
        //加载class文件以及文件夹
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            public boolean accept(File file) {
                return (file.isFile()&&file.getName().endsWith(".class")) || file.isDirectory();
            }
        });

        for (File file:files){
            String fileName = file.getName();
            //class文件
            if(file.isFile()){
                String className = fileName.substring(0,fileName.lastIndexOf("."));
                if(ObjectUtils.isNotAbsNull(packageName)){
                    className = new StringBuilder(packageName).append(".").append(className).toString();
                }
                addClass(classSet,className);
            }else {
                //文件夹
                String subPackagePath = fileName;
                if(ObjectUtils.isNotAbsNull(packagePath)){
                    subPackagePath = packagePath + "/" + fileName;
                }

                String subPackageName = fileName;
                if(ObjectUtils.isNotAbsNull(packageName)){
                    subPackageName = packageName + "."+ fileName;
                }

                addClass(classSet,subPackagePath,subPackageName);
            }
        }

    }

    /**
     * class文件
     * @param classSet
     * @param className
     */
    private static void addClass(Set<Class<?>> classSet,String className){
        classSet.add(loadClass(className,false));
    }
}
